package com.study.springsecurity.controller;

import com.google.code.kaptcha.Producer;
import com.study.springsecurity.utils.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录接口
 */
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private Producer producer;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/getVerifyCode")
    public void getVerifyCode() throws IOException {
        String text = producer.createText();
        HttpSession session = request.getSession();
        session.setAttribute("cacheVerificationCode", text);
        BufferedImage image = producer.createImage(text);
        response.setContentType("image/jpeg");
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }
    }

    /**
     * 跳转到index页面
     *
     * @return
     */
    @GetMapping("/index")
    public String index() {
        log.info("用户：{}，用户id：{}，登录成功！！！", SecurityContextUtil.getUserName(), SecurityContextUtil.getUserId());
        return "home.html";
    }

    /**
     * 登录成功，转发请求
     * 注:该因为登录请求时post，所以转发的请求叶必须时post
     *
     * @return
     */
    @PostMapping("/forward")
    public String forward() {
        log.info("用户：{}，用户id：{}，登录成功，进行请求转发！！！", SecurityContextUtil.getUserName(), SecurityContextUtil.getUserId());
        return "forward_home.html";
    }

    /**
     * 登录失败
     *
     * @return
     */
    @GetMapping("/fail")
    public String fail() {
        return "登录失败" + SecurityContextUtil.getUserName();
    }
}
